package com.xiyuan.smartutils.logging;

import com.xiyuan.smartutils.StrUtils;
import com.xiyuan.smartutils.Validates;
import com.xiyuan.smartutils.logging.appender.ConsoleAppender;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * the description for class LogManager
 *
 * @author xiyuan-lgz 2022-10-19 @version v1.0.0 新建与整理
 */
public final class LoggerManager {
    
    private static Map<String, Logger> loggerMap = new HashMap<String, Logger>();
    private static Map<String, LogConfig> configMap = new HashMap<>();
    private static ConsoleAppender console = new ConsoleAppender();// 全局日志输出器
    
    protected static ConsoleAppender getConsole() {
        return console;
    }
    
    protected static Logger getLogger(String name) {
        configMap.computeIfAbsent(name, (k) -> new LogConfig());
        return loggerMap.computeIfAbsent(name, LoggerImpl::new);
    }
    
    protected static void reportError(Throwable e, String message) {
        System.err.println("LoggerManager reportError caught:" + message);
        e.printStackTrace(System.err);
    }
    
    public static void reportError(Throwable e) {
        reportError(e, "");
    }
    
    /**
     * 添加一项配置 add or update config
     *
     * @param name   logName
     * @param config config
     */
    public static void addConfig(String name, LogConfig config) {
        if (config != null) {
            configMap.put(name, config);
        }
    }
    
    /**
     * 获取日志配置器
     *
     * @param name 日志名称
     * @return 日志配
     */
    public static LogConfig getConfig(String name) {
        return configMap.get(name);
    }
    
    
    /**
     * 设置控制台全局日志 输出配置
     *
     * @param config 配置对象
     */
    public static void setConsoleConfig(LogConfig config) {
        console.setConfig(config);
    }
    
    /**
     * 设置全局日志输出 格式
     *
     * @param partten
     */
    public static void setConsolePartten(String partten) {
        console.getConfig().setPattern(partten);
    }
    
    public static void initConfig(Map<String, ConfigItem> map) {
        Optional.ofNullable(map).ifPresent(m -> m.forEach((k, v) -> {
            k = StrUtils.trim(k);
            if (Validates.isBlank(k) || v == null) {
                return;
            }
            
            LogConfig config = new LogConfig().init(v);
            if ("console".equals(k)) {
                setConsoleConfig(config);
            }
            
            addConfig(k, config);
        }));
    }
}
